
#include "deprecated/CCString.h"
#include "TiledMap.h"
#include "TiledParser.h"
#include "TiledLayer.h"
#include "base/CCData.h"
#include "CCFileUtils.h"
#include "Path.h"

namespace Tiled {

TmxMap* TmxMap::create(const char* tmxFile) {
	Data data = FileUtils::getInstance()->getDataFromFile(tmxFile);
	return create((const char*)data.getBytes(), data.getSize(), Path::getParentPath(tmxFile).c_str());
}

TmxMap* TmxMap::create(const char* tmxString, size_t size, const char* resourcePath)
{
    TmxMap *ret = new (std::nothrow) TmxMap();
	if (ret->init(tmxString, size, resourcePath))
    {
        ret->autorelease();
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return nullptr;
}

bool TmxMap::init(const char* tmxString, size_t size, const char* resourcePath)
{
    setContentSize(Size::ZERO);

	_tmxInfo = new (std::nothrow) TmxMapInfo();
	CC_SAFE_RETAIN(_tmxInfo);
	_tmxInfo->autorelease();
	_tmxInfo->init(tmxString, size, resourcePath);

	int idx = 0;

	auto& layers = _tmxInfo->getLayers();
	for (const auto &layerInfo : layers) {
		if (layerInfo->visible)
		{
			TmxLayer *child = TmxLayer::create(layerInfo, _tmxInfo);
			addChild(child, idx, idx);

			// update content size with the max size
			const Size& childSize = child->getContentSize();
			Size currentSize = this->getContentSize();
			currentSize.width = std::max(currentSize.width, childSize.width);
			currentSize.height = std::max(currentSize.height, childSize.height);
			this->setContentSize(currentSize);

			idx++;
		}
	}

    return true;
}

TmxMap::TmxMap()
	: _tmxInfo(nullptr)
{
}

TmxMap::~TmxMap()
{
	CC_SAFE_RELEASE_NULL(_tmxInfo);
}

// public
TmxLayer* TmxMap::getLayer(const std::string& layerName) const
{
    CCASSERT(layerName.size() > 0, "Invalid layer name!");
    
    for (auto& child : _children)
    {
        TmxLayer* layer = dynamic_cast<TmxLayer*>(child);
        if(layer)
        {
            if(layerName.compare( layer->getLayerName()) == 0)
            {
                return layer;
            }
        }
    }

    // layer not found
    return nullptr;
}

TmxLayerInfo* TmxMap::getLayerInfo(const std::string& layerName) const
{
	return _tmxInfo->getLayer(layerName);
}

}


